package com.daiyang.librarymanagementsystem2.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.daiyang.librarymanagementsystem2.entity.CaptchaProperties;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class HuTollCaptchaConctroller {
    private Long curTime =30*60*1000L;
    @Resource(name = "captchaProperties")
    private CaptchaProperties captchaProperties;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        LineCaptcha lineCaptcha=CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());
        try {
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "No-cache");
            lineCaptcha.write(response.getOutputStream());
            System.out.println(lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getCode(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @RequestMapping("/check")
    public boolean checkCaptccha(String captcha,HttpSession session) {
        Long time=(Long) session.getAttribute(captchaProperties.getSession().getDate());
        String code=(String)session.getAttribute(captchaProperties.getSession().getCode());
        System.out.println(time);
        System.out.println(code);
        System.out.println(captcha);
        if(!StringUtils.hasLength(code)||time==null||(System.currentTimeMillis()-time)>curTime){
            return false;
        }
        if(code.equalsIgnoreCase(captcha)){
            return true;
        }
        return false;
    }

}

